package cn.iocoder.yudao.module.book.controller.app.lock;

import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.book.controller.admin.checkIn.vo.CheckInPageReqVO;
import cn.iocoder.yudao.module.book.controller.app.bookcase.vo.AppBooksRespVO;
import cn.iocoder.yudao.module.book.controller.app.lock.vo.AppCheckInRespVO;
import cn.iocoder.yudao.module.book.controller.app.lock.vo.AppCheckInSaveReqVO;
import cn.iocoder.yudao.module.book.controller.app.lock.vo.AppCheckInEnhancedRespVO;
import cn.iocoder.yudao.module.book.dal.dataobject.checkIn.CheckInDO;
import cn.iocoder.yudao.module.book.service.books.BooksService;
import cn.iocoder.yudao.module.book.service.checkIn.CheckInService;
import cn.iocoder.yudao.module.book.service.records.RecordsService;
import cn.iocoder.yudao.module.book.dal.dataobject.records.RecordsDO;
import cn.iocoder.yudao.module.book.service.users.userDTOService;
import cn.iocoder.yudao.module.book.dal.dataobject.users.userDTODO;
import cn.iocoder.yudao.module.book.constants.UserConstants;
import com.alibaba.fastjson.JSON;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.module.book.enums.ErrorCodeConstants.*;

@Tag(name = "用户 APP - 打卡")
@RestController
@RequestMapping("/api/user")
public class AppCheckInController {

    @Resource
    private CheckInService checkInService;

    @Resource
    private userDTOService userService;

    @Resource
    private BooksService booksService;

    @Resource
    private RecordsService recordsService;

    @Resource
    private BooksService bookService;


    @GetMapping("/clock/list")
    @Operation(summary = "获得打卡记录")
    public CommonResult<PageResult<AppCheckInRespVO>> getuserDTOPage(@Valid CheckInPageReqVO pageReqVO) {
        PageResult<CheckInDO> pageResult = checkInService.getCheckInPage(pageReqVO);
        return success(BeanUtils.toBean(pageResult, AppCheckInRespVO.class));
    }

    @PostMapping("/clock/checkIn")
    @Operation(summary = "创建打卡（通用，已废弃，推荐使用学习打卡或班级打卡）")
    @Deprecated
    public CommonResult<Integer> checkIn(@Valid @RequestBody String content) {
        AppCheckInSaveReqVO reqVO = new AppCheckInSaveReqVO();
        Long userId=userService.getCurrentUserId();
        String time= LocalDate.now().toString();
        List<RecordsDO> recordsDO=recordsService.selectDayRecord(userId,time);//查询今日阅读记录
//        如果没有记录，则不能打卡
        if(recordsDO.isEmpty()){
            throw exception(RECORDS_NOT_EXISTS);
        }else{
//            将阅读记录的绘本id添加到bookList中
            List<Integer> bookList=new ArrayList<>();
            for(RecordsDO s:recordsDO){
                bookList.add(s.getBookId());
            }
            int days=checkInService.selectDayCount(userId)+1;
            reqVO.setUserId(userService.getCurrentUserId())
                    .setBookList(JSON.toJSONString(bookList))
                    .setContent(content)
                    .setDayCount(days)
                    .setCheckInType(1) // 默认学习打卡
                    .setCreateTime(LocalDateTime.now());
            return CommonResult.success(checkInService.AppcreateCheckIn(reqVO));
        }

    }

    @PostMapping("/clock/study-checkIn")
    @Operation(summary = "学习打卡")
    public CommonResult<Integer> studyCheckIn(@RequestBody String content) {
        AppCheckInSaveReqVO reqVO = new AppCheckInSaveReqVO();
        Long userId = userService.getCurrentUserId();
        String time = LocalDate.now().toString();
        List<RecordsDO> recordsDO = recordsService.selectDayRecord(userId, time);//查询今日阅读记录
        
        // 如果没有记录，则不能打卡
        if(recordsDO.isEmpty()){
            throw exception(RECORDS_NOT_EXISTS);
        } else {
            // 将阅读记录的绘本id添加到bookList中
            List<Integer> bookList = new ArrayList<>();
            for(RecordsDO s : recordsDO){
                bookList.add(s.getBookId());
            }
            int days = checkInService.selectDayCount(userId) + 1;
            reqVO.setUserId(userId)
                    .setBookList(JSON.toJSONString(bookList))
                    .setContent(content)
                    .setDayCount(days)
                    .setCheckInType(1) // 设置为学习打卡类型
                    .setCreateTime(LocalDateTime.now());
            return CommonResult.success(checkInService.createStudyCheckIn(reqVO));
        }
    }

    @PostMapping("/clock/class-checkIn")
    @Operation(summary = "班级打卡")
    public CommonResult<Integer> classCheckIn(@RequestBody AppCheckInSaveReqVO reqVO) {
        // 手动验证必要字段
        if (reqVO.getContent() == null || reqVO.getContent().trim().isEmpty()) {
            return CommonResult.error(400, "打卡内容不能为空");
        }
        if (reqVO.getClassId() == null) {
            return CommonResult.error(400, "班级ID不能为空");
        }
        
        Long userId = userService.getCurrentUserId();
        String time = LocalDate.now().toString();
        
        // 班级打卡可以不依赖今日阅读记录，但如果有阅读记录，则自动添加
        List<RecordsDO> recordsDO = recordsService.selectDayRecord(userId, time);
        List<Integer> bookList = new ArrayList<>();
        if (!recordsDO.isEmpty()) {
            for(RecordsDO s : recordsDO){
                bookList.add(s.getBookId());
            }
        }
        
        // 确保bookList不为空字符串，至少是空数组的JSON
        String bookListJson = JSON.toJSONString(bookList);
        if (bookListJson == null || bookListJson.trim().isEmpty()) {
            bookListJson = "[]";
        }
        
        int days = checkInService.selectDayCount(userId) + 1;
        reqVO.setUserId(userId)
                .setBookList(bookListJson)
                .setDayCount(days)
                .setCheckInType(2) // 设置为班级打卡类型
                .setCreateTime(LocalDateTime.now());
        
        return CommonResult.success(checkInService.createClassCheckIn(reqVO));
    }

    @GetMapping("/book/todayReadList")
    @Operation(summary = "今日已读列表")
    public CommonResult<List<AppBooksRespVO>> todayReadList() {
        CheckInDO checkInDO= checkInService.selectBook(userService.getCurrentUserId(), LocalDate.now().toString());
//        如果今日打卡记录不为空，则返回已读列表
        if (checkInDO!=null){
            String bookList=checkInDO.getBookList();
//            解析JSON为List
            List< Integer> booksId=JSON.parseArray(bookList,Integer.class);
            List<AppBooksRespVO> books=new ArrayList<>();
            for(Integer bookId:booksId){
                books.add(bookService.getByBookId(bookId,null));
            }
            return CommonResult.success(books);
        }else{
            throw exception(CHECK_IN_NOT_EXISTS);
        }

    }

    @GetMapping("/clock/enhanced-list")
    @Operation(summary = "获得增强打卡记录列表")
    public CommonResult<PageResult<AppCheckInEnhancedRespVO>> getEnhancedCheckInList(@Valid CheckInPageReqVO pageReqVO) {
        PageResult<CheckInDO> pageResult = checkInService.getCheckInPage(pageReqVO);
        
        // 转换为增强响应VO
        List<AppCheckInEnhancedRespVO> enhancedList = new ArrayList<>();
        for (CheckInDO checkIn : pageResult.getList()) {
            AppCheckInEnhancedRespVO enhancedVO = new AppCheckInEnhancedRespVO();
            enhancedVO.setClockId(checkIn.getClockId());
            enhancedVO.setContent(checkIn.getContent());
            enhancedVO.setDayCount(checkIn.getDayCount());
            enhancedVO.setCreateTime(checkIn.getCreateTime());
            
            // 获取用户信息
            userDTODO user = userService.getuserDTO(checkIn.getUserId());
            if (user != null) {
                AppCheckInEnhancedRespVO.UserInfo userInfo = new AppCheckInEnhancedRespVO.UserInfo();
                userInfo.setUserId(user.getUserId());
                userInfo.setNickName(user.getNickname());
                userInfo.setAvatar(user.getAvatarUrl() != null ? user.getAvatarUrl() : UserConstants.DEFAULT_AVATAR_URL);
                userInfo.setIsVip(user.getIsMember());
                enhancedVO.setUserInfo(userInfo);
            }
            
            // 获取书籍信息
            if (checkIn.getBookList() != null && !checkIn.getBookList().isEmpty()) {
                List<Integer> bookIds = JSON.parseArray(checkIn.getBookList(), Integer.class);
                List<AppCheckInEnhancedRespVO.BookInfo> bookInfoList = new ArrayList<>();
                
                for (Integer bookId : bookIds) {
                    AppBooksRespVO book = bookService.getByBookId(bookId, null);
                    if (book != null) {
                        AppCheckInEnhancedRespVO.BookInfo bookInfo = new AppCheckInEnhancedRespVO.BookInfo();
                        bookInfo.setBookId(book.getBookId());
                        bookInfo.setTitle(book.getTitle());
                        bookInfo.setImage(book.getImage());
                        bookInfo.setCollectionId(book.getCollectionId());
                        bookInfo.setCreator(book.getCreator());
                        bookInfoList.add(bookInfo);
                    }
                }
                enhancedVO.setBookList(bookInfoList);
            }
            
            enhancedList.add(enhancedVO);
        }
        
        return success(new PageResult<>(enhancedList, pageResult.getTotal()));
    }

    @GetMapping("/clock/class-list/{classId}")
    @Operation(summary = "获取班级打卡记录")
    public CommonResult<PageResult<AppCheckInEnhancedRespVO>> getClassCheckInList(
            @PathVariable("classId") Integer classId,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer pageSize) {
        
        CheckInPageReqVO pageReqVO = new CheckInPageReqVO();
        pageReqVO.setPageNo(page);
        pageReqVO.setPageSize(pageSize);
        
        PageResult<CheckInDO> pageResult = checkInService.getClassCheckInPage(classId, pageReqVO);
        
        // 转换为增强响应格式
        List<AppCheckInEnhancedRespVO> enhancedList = new ArrayList<>();
        
        for (CheckInDO checkIn : pageResult.getList()) {
            AppCheckInEnhancedRespVO enhancedVO = new AppCheckInEnhancedRespVO();
            enhancedVO.setClockId(checkIn.getClockId());
            enhancedVO.setContent(checkIn.getContent());
            enhancedVO.setDayCount(checkIn.getDayCount());
            enhancedVO.setCreateTime(checkIn.getCreateTime());
            
            // 用户信息
            userDTODO user = userService.getuserDTO(checkIn.getUserId());
            if (user != null) {
                AppCheckInEnhancedRespVO.UserInfo userInfo = new AppCheckInEnhancedRespVO.UserInfo();
                userInfo.setUserId(user.getUserId());
                String nick = user.getNickname();
                if (nick == null || nick.trim().isEmpty()) {
                    nick = "微信用户_" + String.valueOf(user.getUserId()).substring(Math.max(0, String.valueOf(user.getUserId()).length() - 4));
                }
                userInfo.setNickName(nick);
                userInfo.setAvatar(user.getAvatarUrl() != null ? user.getAvatarUrl() : UserConstants.DEFAULT_AVATAR_URL);
                userInfo.setIsVip(user.getIsMember());
                enhancedVO.setUserInfo(userInfo);
            }
            
            // 书籍信息（优先使用打卡记录的bookList；为空则回退到当天阅读记录）
            List<AppCheckInEnhancedRespVO.BookInfo> bookInfoList = new ArrayList<>();
            if (checkIn.getBookList() != null && !checkIn.getBookList().isEmpty()) {
                List<Integer> bookIds = JSON.parseArray(checkIn.getBookList(), Integer.class);
                for (Integer bookId : bookIds) {
                    AppBooksRespVO book = booksService.getByBookId(bookId, null);
                    if (book != null) {
                        AppCheckInEnhancedRespVO.BookInfo bookInfo = new AppCheckInEnhancedRespVO.BookInfo();
                        bookInfo.setBookId(book.getBookId());
                        bookInfo.setTitle(book.getTitle());
                        bookInfo.setImage(book.getImage());
                        bookInfo.setCollectionId(book.getCollectionId());
                        bookInfo.setCreator(book.getCreator());
                        bookInfoList.add(bookInfo);
                    }
                }
            }
            if (bookInfoList.isEmpty() && checkIn.getCreateTime() != null) {
                String day = checkIn.getCreateTime().toLocalDate().toString();
                List<RecordsDO> dayRecords = recordsService.selectDayRecord(checkIn.getUserId(), day);
                for (RecordsDO record : dayRecords) {
                    AppBooksRespVO book = booksService.getByBookId(record.getBookId(), null);
                    if (book != null) {
                        AppCheckInEnhancedRespVO.BookInfo bookInfo = new AppCheckInEnhancedRespVO.BookInfo();
                        bookInfo.setBookId(book.getBookId());
                        bookInfo.setTitle(book.getTitle());
                        bookInfo.setImage(book.getImage());
                        bookInfo.setCollectionId(book.getCollectionId());
                        bookInfo.setCreator(book.getCreator());
                        bookInfoList.add(bookInfo);
                    }
                }
            }
            if (!bookInfoList.isEmpty()) {
                enhancedVO.setBookList(bookInfoList);
            }
            
            enhancedList.add(enhancedVO);
        }
        
        return success(new PageResult<>(enhancedList, pageResult.getTotal()));
    }

    @GetMapping("/clock/study-list")
    @Operation(summary = "获取学习打卡记录")
    public CommonResult<PageResult<AppCheckInRespVO>> getStudyCheckInList(@Valid CheckInPageReqVO pageReqVO) {
        // 设置查询条件：只查询学习打卡（类型为1）
        pageReqVO.setCheckInType(1);
        pageReqVO.setUserId(userService.getCurrentUserId().intValue());
        PageResult<CheckInDO> pageResult = checkInService.getCheckInPage(pageReqVO);
        return success(BeanUtils.toBean(pageResult, AppCheckInRespVO.class));
    }
}
